<template>
  <div class="container">
    <el-form
      :model="formData"
      label-width="100px"
      style="width: 800px"
      :rules="rules"
      ref="formRef"
      hide-required-asterisk
    >
      <!-- 第一行：姓名和性别 -->
      <el-row class="row1 form-row">
        <el-form-item label="姓名" prop="userName"  >
          <el-input v-model="formData.userName"></el-input>
        </el-form-item>
        <el-form-item label="性别">
          <el-select v-model="formData.sex" placeholder="请选择性别">
            <el-option label="男" value="男"></el-option>
            <el-option label="女" value="女"></el-option>
          </el-select>
        </el-form-item>
      </el-row>
      <!-- 第二行：电话和账号 -->
      <el-row class="form-row">
        <el-form-item label="电话" prop="tel">
          <el-input v-model="formData.tel" placeholder="请输入电话"></el-input>
        </el-form-item>
        <el-form-item label="账号">
          <el-input v-model="formData.account" disabled></el-input>
        </el-form-item>
      </el-row>
      <!-- 第三行：密码 -->
      <el-row class="form-row">
        <el-form-item label="密码" prop="password">
          <el-input v-model="formData.password" type="password" placeholder="请输入新密码"></el-input>
        </el-form-item>
      </el-row>
      <!-- 第四行：修改按钮居中 -->
      <el-row class="form-row">
        <el-button type="primary" @click="handleModify">修改</el-button>
      </el-row>
    </el-form>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getUserInfo, updateUserInfo } from '../api/System'
import { useRouter } from 'vue-router'
const router = useRouter()

// 本地存储
const user = JSON.parse(localStorage.getItem('user'))

const formData = ref({})

const flag = ref(false)

const oldformData = ref({})
// 根据用户 id 获取用户信息
function getUserInfoById() {
  let data = {
    userId: user.userId,
  }
  getUserInfo('userById', data).then((res) => {
    if (res.code == 200) {
      formData.value = res.dataset
      oldformData.value = JSON.parse(JSON.stringify(res.dataset));
    }
  })
}
onMounted(() => {
  getUserInfoById()
})

// 修改信息
function handleModify1() {
  let data = {
    userId: user.userId,
    userName: formData.value.userName,
    department: formData.value.department,
    sex: formData.value.sex,
    roleId: formData.value.roleId,
    password: formData.value.password,
    account: formData.value.account,
    tel: formData.value.tel,
  }
  if (formData.value.password !=oldformData.value.password) {
    flag.value = true
  }

  updateUserInfo('updateUser', data).then((res) => {
    if (res.code == 200) {
      ElMessage.success('修改成功')
      //清除本地index
      if (flag.value) {
        sessionStorage.removeItem('activeIndex')
      //跳转到登录页面
      setTimeout(() => {
        router.push('/')
        // window.location.href = '/'
      }, 1000)
      }
    
      
    }
  })
}
const formRef = ref(null)
const handleModify = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      ElMessageBox.confirm('是否修改信息？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          handleModify1()
        })
        .catch(() => {
          ElMessage.info('已取消修改')
        })
    }
  })
}
// 表单验证规则
const rules = {
  userName: [
    { required: true, message: '姓名不能为空', trigger: 'blur' },
    { min: 2, max: 10, message: '姓名长度在 2 到 10 个字符', trigger: 'blur' },
  ],
  tel: [
    { 
      validator: (rule, value, callback) => {
        if (![1, 2].includes(user.roleId) && !value) {
          callback(new Error('电话不能为空'))
        } else {
          callback()
        }
      },
      trigger: ['blur', 'change']
    },
    { 
      pattern: /^1[3456789]\d{9}$/, 
      message: '请输入正确的手机号码', 
      trigger: ['blur', 'change'] 
    }
  ],
  password: [
    { 
      validator: (rule, value, callback) => {
        if (value && (value.length < 5 || value.length > 20)) {
          callback(new Error('密码长度需在5-20位之间'))
        } else {
          callback()
        }
      },
      trigger: 'blur' 
    }
  ],
}
</script>

<style scoped>
/* 可以根据需要添加更多样式 */
.container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
}
.el-form {
  width: 800px;
  background-color: #fff;
  padding: 20px;
  box-shadow: 4px 4px 4px rgba(0, 0, 0, 0.1);
  border-radius: 20px;
}
.el-row {
  margin-bottom: 20px;
}
button {
  background-color: #0f6ab1;
}
.row1 {
  margin-top: 20px;
}
.el-select {
  width: 200px;
}
/* 自定义表单行样式 */
.form-row {
  display: grid;
  grid-template-columns: repeat(2, 1fr); /* 两列布局 */
  justify-items: center; /* 表单项水平居中 */
}

/* 第四行按钮样式，单独处理 */
.form-row:last-child {
  display: flex;
  justify-content: center;
  grid-template-columns: none; /* 移除网格布局 */
}
/* 表单项样式 */
.el-form-item {
  margin-bottom: 0;
}
</style>